<?php

declare(strict_types=1);

namespace Newbie;

use DateTimeInterface;
use Newbie\Traits\ModelMacroTrait;

/**
 * Class NewbieModel
 * @package Newbie
 */
class NewbieModel extends \support\Model {
    use ModelMacroTrait;

    public $incrementing = false;

    protected $primaryKey = 'id';

    /**
     * 隐藏的字段列表
     * @var string[]
     */
    protected $hidden = ['deleted_at'];

    protected $dateFormat = 'Y-m-d H:i:s';

    /**
     * 状态
     */
    public const ENABLE = '0';
    public const DISABLE = '1';

    /**
     * 默认每页记录数
     */
    public const PAGE_SIZE = 15;

    /**
     * NewbieModel constructor.
     */
    public function __construct (array $attributes = []) {
        parent::__construct($attributes);
        //注册常用方法
        $this->registerBase();
        //注册权限
        $this->registerUserDataScope();

    }


    /**
     * 模型的 "booted" 方法
     *
     * @return void
     */
    protected static function booted () {
        //统一的模型主键
        static::saving(function ($modelInstant) {
            // 生成ID
            if ($modelInstant instanceof NewbieModel &&
                !$modelInstant->incrementing &&
                $modelInstant->getPrimaryKeyType() === 'int' &&
                empty($modelInstant->{$modelInstant->getKeyName()})
            ) {
                //整形未设置自增主键使用snowflake
                $modelInstant->setPrimaryKeyValue(snowflake_id());
            }
        });
    }

    /**
     * 设置主键的值
     * @param string | int $value
     */
    public function setPrimaryKeyValue ($value): void {
        $this->{$this->primaryKey} = $value;
    }

    /**
     * @return string
     */
    public function getPrimaryKeyType (): string {
        return $this->keyType;
    }

    /**
     * @param array $models
     * @return NewbieCollection
     */
    public function newCollection (array $models = []): NewbieCollection {
        return new NewbieCollection($models);
    }

    /**
     * @param TimeInterface $date
     * @return string
     */
    protected function serializeDate (DateTimeInterface $date): string {
        return $date->format('Y-m-d H:i:s');
    }
}